package ani.trainning.cacobatph.situation;

import java.io.IOException;
import java.util.Dictionary;
import java.util.Hashtable;

import org.json.JSONObject;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import ani.trainning.cacobatph.ConstantUtil;
import ani.trainning.cacobatph.R;
import ani.trainning.cacobatph.utilities;
import ani.trainning.cacobatph.dac.ACT3_DACprincipale;

public class Thr10_Situation {

	public static final int ERREUR_LOCAL = -1;
	public static final int ERREUR_WS = 0;
	public static final int RESULT_OK = 1;

	private final Handler mHandler;
	private final Context context;
	boolean noErrorServer = true;

	String user;
	String pass;

	// constructor
	public Thr10_Situation(Handler handler, Context context,String _user, String _pass) {
		mHandler = handler;
		this.context = context;
		this.user=_user;
		this.pass=_pass;
	}

	public Thread createThread() {
		return new Thread() {
			@Override
			public void run() {
				// creation du message.
				try {
					String url = context.getString(R.string.WS7_DAC);
					Dictionary<String, String> params = new Hashtable<String, String>();
					params.put(ConstantUtil.KEY_USERNAME, user);
					params.put(ConstantUtil.KEY_PASSWORD, pass);
					String response = decoderJson(utilities.getContent(url, params));
					
					Message msg=new Message();
					msg.what = RESULT_OK;
					msg.obj = response;
					if(!noErrorServer)
						msg.what = ERREUR_WS;
					mHandler.sendMessage(msg);

				} 	catch (IOException e) {
					Log.e("thread exeption : ", ""+e.getMessage());
					mHandler.sendEmptyMessage(ACT3_DACprincipale.EXEPTION_IO);
				}catch (Exception e) {
					Log.e("thread exeption : ", ""+e.getMessage());
					mHandler.sendEmptyMessage(ACT3_DACprincipale.EXEPTIONS);
				}

			}
		};
	}

	private String decoderJson(String response) throws Exception{

		JSONObject jSon = new JSONObject(response);
		int code = jSon.getInt("code");
		switch (code) {
		case 3:
			return jSon.getString("description");
		case 4:
			return jSon.getString("description");
		case 5:
			noErrorServer = false;
			return response;
		default:
			return response;
		}
	}
}
